package com.bifrost.admin.controller;

import com.alibaba.fastjson.JSONObject;
import com.bifrost.annotation.CurrentAdmin;
import com.bifrost.annotation.CurrentStore;
import com.bifrost.common.model.ResultModel;
import com.bifrost.exception.KnownRuntimeException;
import com.bifrost.model.ProductAddModel;
import com.bifrost.model.ro.KeywordBatchRO;
import com.bifrost.model.ro.KeywordRO;
import com.bifrost.model.ro.ProductImgUploadRO;
import com.bifrost.model.vo.PageVO;
import com.bifrost.service.*;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

/**
 * @author Lee
 * Create Class on 2018/6/27
 * @com.bifrost.admin.controller
 * @wechat-mall
 */
@RestController
@Api("后台商品相关接口")
@RequestMapping("/admin/product")
@Slf4j
public class AdminProductController {

    @Autowired
    ProductService productService;
    @Autowired
    ProductSkuService productSkuService;
    @Autowired
    MallService mallService;
    @Autowired
    ProductSkuService skuService;
    @Autowired
    StoreService storeService;
    @Autowired
    AdminUserService userService;

    @ApiOperation(value = "商品分页查询")
    @ApiImplicitParams({@ApiImplicitParam(name = "key" ,value = "商品名称" , dataType = "String" , paramType = "query"),
            //skucode . brandName , categoryName
            @ApiImplicitParam(name = "available" ,value = "上下架" , dataType = "String" , paramType = "query"),
            @ApiImplicitParam(name = "externalIds" ,value = "SAP编码" , dataType = "String" , paramType = "query"),
            @ApiImplicitParam(name = "minPrice" ,value = "最低价" , dataType = "String" , paramType = "query" ),
            @ApiImplicitParam(name = "maxPrice" ,value = "最高价" , dataType = "String" , paramType = "query" ),
            @ApiImplicitParam(name = "sortOrder" ,value = "排序{0:综合排序，1：价格升序，2：价格降序，3：销量降序}" , dataType = "String" , paramType = "query", defaultValue = "0"),
            @ApiImplicitParam(name = "brandName" ,value = "品牌Id" , dataType = "String" , paramType = "query" ),
            @ApiImplicitParam(name = "page" ,value = "当前页" , dataType = "Integer" , paramType = "query" , defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize" ,value = "页条数" , dataType = "Integer" , paramType = "query" , defaultValue = "8")})
    @GetMapping("/page")
    public ResultModel findPage(@CurrentStore Long storeId,
                                String storeIds , String externalIds,String categoryName ,  String brandName , String skuName , String minPrice , String maxPrice, String brandId , String available , @RequestParam(value = "sortOrder" , required = false, defaultValue = "0") String sortOrder,
                                @RequestParam( defaultValue = "1") Integer page ,
                                @RequestParam( defaultValue = "8") Integer pageSize,
                                @RequestParam( defaultValue = "true") Boolean isDefault){

        PageVO pageVO = productService.findAllPage(storeService.getMerchantStore(storeId),storeIds, externalIds ,categoryName , brandName, page, pageSize, sortOrder, minPrice, maxPrice, skuName, brandId, available , isDefault);
        return ResultModel.ok().put("result" , pageVO);
    }

    @ApiOperation("/添加商品SKU基本信息+规格")
    @PostMapping(value = "/add", consumes = "application/json")
    public ResultModel addProductSku(@CurrentAdmin Long userId , @RequestBody @Valid ProductAddModel productAddModel , @CurrentStore Long storeId){

        productService.newProduct(userService.findById(userId),productAddModel,storeService.getMerchantStore(storeId));
        return ResultModel.ok();
    }


    @ApiOperation("/修改商品SKU基本信息+规格")
    @PostMapping(value = "/update", consumes = "application/json")
    public ResultModel updateProductSku(@CurrentAdmin Long userId , @RequestBody @Valid  ProductAddModel productAddModel){
        productService.mergeProduct(userService.findById(userId),productAddModel);
        return ResultModel.ok();
    }

    @ApiOperation("/展示商品SKU基本信息+规格")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productId" , value = "查询当前商品信息" , required = true , dataType = "Long" , paramType = "query"),
            @ApiImplicitParam(name = "externalId" , value = "查询当前商品信息" , required = true , dataType = "String" , paramType = "query")
    })
    @GetMapping(value = "/detail")
    public ResultModel getProductSku(Long productId , String externalId){
        if(productId==null&& StringUtils.isBlank(externalId)){
            throw new KnownRuntimeException("商品Id和SAP编码必须选填一个");
        }
        ProductAddModel productAddModel = productService.findProductModelById(productId);
        return ResultModel.ok().put("result",productAddModel);
    }

    @ApiOperation("/展示SAP基本信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "externalId" , value = "查询当前商品信息" , required = true , dataType = "String" , paramType = "query")
    })
    @GetMapping(value = "/sapgoods/detail")
    public ResultModel sapGoodsDetail(@CurrentStore Long storeId , @NotBlank(message = "Sap编码不可以为空")@RequestParam("externalId") String externalId){
        ProductAddModel productAddModel = productService.sapGoodsDetail(storeService.getMerchantStore(storeId),externalId);
        return ResultModel.ok().put("result",productAddModel);
    }

    @ApiOperation("/商品图片批量上传接口")
    @PostMapping(value = "/batch/image")
    public ResultModel batchUploadImage(@CurrentAdmin Long userId,@RequestBody @NotEmpty(message = "批量传图不可以为空") List<ProductImgUploadRO> imgUploadRO){

        try {
            productService.upload(userService.findById(userId), imgUploadRO);
            return ResultModel.ok("上传成功");
        } catch (IOException e) {
            log.error("传图失败..",e);
            return ResultModel.error("上传失败");
        }

    }

    @ApiOperation(value = "关键字查询")
    @PostMapping("/query/keyword")
    public ResultModel batchKeyWordImport(@CurrentStore Long storeId ,
                                          String queryKey,
                                          String storeIds,
                                          String externalIds,
                                          @RequestParam( defaultValue = "1") Integer page ,
                                          @RequestParam( defaultValue = "8") Integer pageSize){

        return ResultModel.ok().put("result",productService.findSkuByKeyWord(externalIds, storeId,storeIds,queryKey,page,pageSize));

    }

    @ApiOperation(value = "关键字批量导入/修改")
    @PostMapping("/batch/keyword")
    public ResultModel batchKeyWordImport(@CurrentAdmin Long userId ,
                                          @CurrentStore Long storeId,
                                          @RequestBody @Valid KeywordBatchRO keywordBatchRO){
        productService.batchKeyWordImport(userService.findById(userId) ,storeId,keywordBatchRO);
        return ResultModel.ok();

    }

    @ApiOperation("查询热门商品")
    @GetMapping("/hotSku")
    public String findSkuHot(@RequestParam(value="page",defaultValue = "1")int page,@RequestParam(value="pageSize",defaultValue = "20")int pageSize){

        PageVO productSkus=productSkuService.findSkuHot(page,pageSize);

        return JSONObject.toJSONString(com.bifrost.model.ResultModel.ok().put("data",productSkus));
    }

    @ApiOperation("商品热门")
    @GetMapping("/updateSkuHot")
    public String updateSkuHot(@RequestParam(value="ids")String ids,@RequestParam(value = "hot")Boolean hot){

        int i=productSkuService.updateSkuHot(ids, hot);
        if (i>0){
            return JSONObject.toJSONString((com.bifrost.model.ResultModel.ok()));
        }

        return JSONObject.toJSONString((com.bifrost.model.ResultModel.error()));
    }


    /*@ApiOperation("/商品上下架")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productId" , value = "商品id" , required = true , dataType = "Long" , paramType = "query"),
            @ApiImplicitParam(name = "available" , value = "商品上下架" , required = true , dataType = "Boolean" , paramType = "query")
    })
    @GetMapping(value = "/update/available")
    public ResultModel updateAvailable(@RequestParam Long productId , @RequestParam Boolean available){
        ServerResponse response = productService.updateAvailable(productId,available);
        if(response.isSuccess()){`
            return ResultModel.ok();
        }
        return ResultModel.error(response.getMsg());
    }

    @ApiOperation("/商品删除")
    @ApiImplicitParam(name = "productId" , value = "商品id" , required = true , dataType = "Long" , paramType = "query")
    @GetMapping(value = "/delete")
    public ResultModel deleteProduct(@RequestParam @NotNull(message = "商品不能为空") Long productId ){
        ServerResponse response = productService.deleteProduct(productId);
        if(response.isSuccess()){
            return ResultModel.ok();
        }
        return ResultModel.error(response.getMsg());
    }*/


}
